package com.zz.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhangbin
 * @Create 2023-02-01 14:22
 * @Description
 */
public class FileUtil {
    private static final int CACHE_SIZE = 1024;

    // 获取文件内容
    public static String fileToBytes(String filePath) {

        File file = new File(filePath);
        byte[] data = new byte[0];
        if (file.exists()) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
                byte[] cache = new byte[CACHE_SIZE];
                int nRead = 0;
                while ((nRead = in.read(cache)) != -1) {
                    out.write(cache, 0, nRead);
                    out.flush();
                }
                out.close();
                in.close();
                data = out.toByteArray();
                //转为字符串
                String contentStr = null;
                try {
                    contentStr = new String(data, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                System.out.println("文件内容为：" + contentStr);

                return contentStr;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return "";

    }


    /**
     * File转byte[]数组
     *
     * @param file
     * @return
     */
    public static byte[] file2byte(File file) {
        if (file == null) {
            return null;
        }
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fileInputStream.read(b)) != -1) {
                byteArrayOutputStream.write(b, 0, n);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * byte[]数组转File
     *
     * @param bytes
     * @param fileFullPath
     * @return
     */
    public static File byte2file(byte[] bytes, String fileFullPath) {
        if (bytes == null) {
            return null;
        }
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(fileFullPath);
            //判断文件是否存在
            if (file.exists()) {
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * File转byte[]数组
     *
     * @param fileFullPath
     * @return
     */
    public static byte[] file2byte(String fileFullPath) {
        if (fileFullPath == null || "".equals(fileFullPath)) {
            return null;
        }
        return file2byte(new File(fileFullPath));
    }


    /**
     * 读取所有子文件
     *
     * @param dirPath //     * @param allFileList
     */
    public static List<File> forEachFile(File dirPath) {
        List<File> allFileList = new ArrayList<>();
        File[] fileList = dirPath.listFiles();
        assert fileList != null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                forEachFile(file);
            } else {
                allFileList.add(file);
            }
        }
        return allFileList;
    }

    /**
     * 读取所有子文件
     */
    public static List<File> getAllFile() {
        String filePath = getRelativeResourceFilePath();
        return forEachFile(new File(filePath));

    }

    /**
     * 获取resource下的uploadFile路径
     *
     * @return
     */
    public static String getResourceWordTemplate() {
        String dir = System.getProperty("user.dir");
        return dir + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "wordTemplate"  + File.separator;
    }

    /**
     * 获取resource下的uploadFile路径
     *
     * @return
     */
    public static String getResourceUploadFilePath() {
        String dir = System.getProperty("user.dir");
        return dir + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "uploadFile";
    }

    /**
     * 获取resource下的uploadFile路径
     *
     * @return
     */
    public static String getResourceFilePath() {
        String dir = System.getProperty("user.dir");
        return dir + File.separator + "src" + File.separator + "main" + File.separator + "resources";
    }

    /**
     * 获取项目路径下的的uploadFile路径
     *
     * @return
     */
    public static String getRelativeResourceFilePath() {
        String dir = System.getProperty("user.dir");
        return dir + File.separator + "uploadFile";
    }

    /**
     * 获取项目路径下的的uploadFile路径
     *
     * @return
     */
    public static String getRelativeResourceFilePathWord() {
        String dir = System.getProperty("user.dir");
        return dir + File.separator + "wordTemplate" + File.separator;
    }


    /**
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！)
     *
     * @param res      原字符串
     * @param filePath 文件路径
     * @return 成功标记
     */
    public static boolean string2File(String res, String filePath) {
        boolean flag = true;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            File distFile = new File(filePath);
            if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            String len;
            while ((len = bufferedReader.readLine()) != null) {
                // 这里因为 单引号 ' 有些问题, 做了下面特殊处理
                len = len.replace("&apos;", "'");
                bufferedWriter.write(len);
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 字符串输出为文件的方法
     *
     * @param fileContent  文件的字符串
     * @param absolutePath 输出路径
     * @return
     */
    public static boolean stringToFile(String fileContent, String absolutePath) {
        boolean result = false;
        java.io.File absolutePathFielName = new java.io.File(absolutePath);
        OutputStream os = null;
        try {
            if (absolutePathFielName.exists()) {
                absolutePathFielName.delete();
            }
            os = new FileOutputStream(absolutePathFielName);
            os.write(fileContent.getBytes());
            os.flush();
            result = true;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void generatorFile(InputStream input, String fileFullPath) {
        //生成文件
        BufferedInputStream in;
        BufferedOutputStream out;
        in = new BufferedInputStream(input);
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileFullPath));
            int len;
            byte[] b = new byte[1024];
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
